<template>
    <div class="account-box">
    <div class="toggle">
      <a @click="isMsgLogin=false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin=true" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form class="form" :validation-schema="schema" v-slot="{ errors }" autocomplete="off" ref="formCom">
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field type="text" placeholder="请输入用户名或手机号" name="account" v-model="form.account" :class="{error:errors.account}"/>
          </div>
          <!-- 表格非法输入提示 -->
          <div class="error" v-if="errors.account"><i class="iconfont icon-warning"/> {{errors.account}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field type="password" placeholder="请输入密码" name="password" v-model="form.password" :class="{error:errors.password}"/>
          </div>
             <!-- 表格非法输入提示 -->
             <div class="error" v-if="errors.password"><i class="iconfont icon-warning"/> {{errors.password}}</div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field type="text" placeholder="请输入手机号"  name="mobile" v-model="form.mobile" :class="{error:errors.mobile}"/>
          </div>
            <!-- 表格非法输入提示 -->
             <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning"/> {{errors.mobile}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field type="text" placeholder="请输入验证码" name="code" v-model="form.code" :class="{error:errors.code}"/>
            <span class="code" @click="getIdentiFying()">{{timer===0? '发送验证码':`${timer}秒后重试`}}</span>
          </div>
          <!-- 表格非法输入提示 -->
             <div class="error" v-if="errors.code"><i class="iconfont icon-warning"/> {{errors.code}}</div>
        </div>
      </template>
       <div class="form-item">
        <div class="agree">
           <Field as='XtxCheckbox' name="isAgree" v-model="form.isAgree" />
          <!-- <XtxCheckbox name="isAgree" v-model="form.isAgree" /> -->
          <!-- {{form.isAgree}} -->
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree">
          <i class="iconfont icon-warning" />
          {{errors.isAgree}}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </Form>
    <div class="action">
      <!-- <span id="qqLoginBtn"></span> -->
<a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
<img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
</a>
        <!-- <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt=""> -->

      <!-- <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt=""> -->
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import { reactive, ref, watch } from 'vue'
import { Field, Form } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import Message from '@/components/library/message'
import { accountLogin, phoneNumber, identiFying } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { useIntervalFn } from '@vueuse/core'
// import QC from 'qc'
// import Message from '@/components/library/message'
export default {
  name: 'LoginForm',
  components: { Form, Field },
  setup () {
    // const { proxy } = getCurrentInstance()
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const isMsgLogin = ref(false)
    const formCom = ref(null)
    const form = reactive({
      isAgree: false,
      account: null,
      password: null,
      mobile: null,
      code: null
    })
    console.log(form.isAgree)
    // 表单校验
    const mySchema = {
      account: schema.account,
      password: schema.password,
      mobile: schema.mobile,
      code: schema.code,
      isAgree: schema.isAgree
    }
    // 监听切换，清除校验数据和重置表单
    watch(isMsgLogin, () => {
      form.isAgree = false
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
      // 清除校验结果
      formCom.value.resetForm()
    })
    // pause暂停，resume开始
    const timer = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      console.log(123435)
      timer.value--
      if (timer.value === 0) {
        pause()
      }
    }, 1000, false)
    // 点击发送验证码
    const getIdentiFying = () => {
      // 验证手机号格式
      const valid = mySchema.mobile(form.mobile)
      console.log(valid)
      if (valid === true) {
        console.log(timer)
        if (timer.value === 0) {
          console.log('验证码发送成功')
          const { mobile } = form
          identiFying(mobile).then(data => {
            console.log(data.result)
            // 开始计时
            timer.value = 100
            resume()
            Message({ type: 'success', text: '验证码发送成功' })
          }).catch(e => {
            Message({ type: 'error', text: e.response.data.message })
          })
        }
        console.log(111)
      } else {
        // 使用vee库的错误函数显示错误信息，setFieldError(字段，错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
      // console.log(valid)
      // console.log('验证码发送成功')
      // const { mobile } = form
      // identiFying({ mobile }).then(data => {
      //   console.log(data.result)
      // })
    }
    const login = async () => {
      if (!isMsgLogin.value) {
        console.log('账号登录')
        // 表单验证validate()返回的是Promise
        formCom.value.validate().then(valid => {
          console.log(valid)
          console.log(valid)
          if (valid) {
            const { account, password } = form
            // 存储用户信息
            accountLogin({ account, password }).then(data => {
              const { id, avatar, nickname, account, mobile, token } = data.result
              store.commit('user/setUser', { id, avatar, nickname, account, mobile, token })
              console.log(route.query.redirectUrl)
              //合并数据
              store.dispatch('car/mergCar').then(()=>{
                 router.push(store.state.user.redirectUrl)
                 Message({ type: 'success', text: '登录成功' })
              })
             
            }).catch((e) => {
              console.log(e.response.data)
              if (e.response.data) {
                Message({ type: 'error', text: e.response.data.message })
              }
            })
          }
        })
      } else {
        console.log('密码登录')
        formCom.value.validate().then(valid => {
          console.log(valid)
          if (valid) {
            const { mobile, code } = form
            phoneNumber({ mobile, code }).then(data => {
              const { id, avatar, nickname, account, mobile, token } = data.result
              store.commit('user/setUser', { id, avatar, nickname, account, mobile, token })
              console.log(route.query.redirectUrl)
              //合并数据
            store.dispatch('car/mergCar').then(()=>{
               router.push(route.query.redirectUrl || '/')
              Message({ type: 'success', text: '登录成功' })
            })
             
            })
          }
        })
      }

      // Message({ type: 'error', text: '出错了' })
      // 此处是调用原型上挂载的函数
      // proxy.$Message({ type: 'error', text: '出错了' })
    }
    // onMounted(() => {
    //   QC.Login({
    //     btnId: 'qqLoginBtn'
    //   })
    // })
    return { isMsgLogin, form, schema: mySchema, formCom, login, getIdentiFying, timer }
  }
}
</script>
<style scoped lang="less">
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
